import { observable, action } from 'mobx';

import { list, info } from "../apis/function";

const funcCache = {};

export default class FunctionStore {
    @observable functions = []; // 函数列表
    @observable categorys = []; // 函数分类
    @observable currCategory = "all"; // 当前所选分类 默认为全部
    @observable currFunc = {}; // 当前所选择的函数
    @observable currFuncInfo = {}; // 当前所选函数的详细信息
    @observable currPage = 1; // 当前页
    @observable pageSize = 5; // 每页显示函数的数量
    @observable searchText = ""; // 函数搜索关键字

    // 获取函数列表
    @action getFunctionList = () => {
        const store = this;
        
        return list().then(res => {
            let data = res.data || [];

            if(!data.length) return;

            let functions = [];
            let categorys = [];
            data.forEach(categoryFuncs => {
                let { categoryText, categoryName } = categoryFuncs;

                categorys.push({
                    name: categoryName,
                    text: categoryText
                });
                
                functions.push.apply(functions, categoryFuncs.items.map(item => {
                    item.category = categoryName;
                    return item;
                }));
            });
            store.functions = functions;
            store.categorys = categorys;
            store.onCurrFuncChange(functions[0]);
        });
    }

    // 获取函数详情
    @action getFuncInfo = funcId => {
        const store = this;
        let funcInfo = funcCache[funcId];
        
        if(funcInfo) return ( store.currFuncInfo = funcInfo );

        info(funcId).then(res => {
            funcInfo = res.data;

            if(!funcInfo) return;

            store.currFuncInfo = res.data;
            funcCache[funcInfo.id] = funcInfo;
        });
    }

    // 搜索关键字变更
    @action onSearchTextChange = searchText => {
        this.searchText = searchText.toLowerCase();
        this.onCurrPageChange(1);
    }

    // 当前函数分类变更
    @action onCurrCategoryChange = currCategory => {
        this.currCategory = currCategory;
        this.onCurrPageChange(1);
    }

    // 当前所选函数变更
    @action onCurrFuncChange = currFunc => {
        this.currFunc = currFunc;
        this.getFuncInfo(currFunc.id);
    }

    // 当前页
    @action onCurrPageChange = currPage => {
        this.currPage = currPage;
    }
}